package org.carl.base.driving.service.receive.impl;

import cn.hutool.core.util.StrUtil;
import com.pugwoo.dbhelper.DBHelper;
import com.pugwoo.dbhelper.impl.SpringJdbcDBHelper;
import lombok.extern.slf4j.Slf4j;
import org.carl.base.driving.DriveManage;
import org.carl.base.driving.core.ReceiveExecute;
import org.carl.base.driving.entity.ReceiveMessage;
import org.carl.base.driving.service.receive.ReceiveMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 消息接收服务
 */
@Slf4j
@Service
@ConditionalOnBean(value ={DriveManage.class})
public class ReceiveMessageServiceImpl implements ReceiveMessageService {

    @Autowired
    private DBHelper dbHelper;

    public void insert(ReceiveMessage receiveMessage) {
        receiveMessage.setVersion(0);
        receiveMessage.setGmtModify(new Date());
        int total = dbHelper.insert(receiveMessage);
        if (total <= 0) {
            throw new RuntimeException("系统异常");
        }
    }

    public void update(ReceiveMessage receiveMessage) {
        dbHelper.update(receiveMessage);
    }

    public void deleteById(String receiveId) {
        dbHelper.deleteByKey(receiveId);
    }

    public ReceiveMessage selectById(String receiveId) {
        if (StrUtil.isEmpty(receiveId)) {
            return null;
        }
        return dbHelper.getByKey(ReceiveMessage.class, receiveId);
    }

    public void updateHandleState(String receiveId, Integer handleState) {
        if (StrUtil.isEmpty(receiveId) || handleState == null) {
            throw new RuntimeException("参数错误");
        }
        ReceiveMessage receiveMessageUpdate = new ReceiveMessage();
        receiveMessageUpdate.setReceiveId(receiveId);
        receiveMessageUpdate.setHandleState(handleState);

        update(receiveMessageUpdate);
    }

    public List<ReceiveMessage> findBySendId(String sendId) {
        if (StrUtil.isEmpty(sendId)) {
            return Collections.emptyList();
        }
        return dbHelper.getAll(ReceiveMessage.class, "and send_id=?", sendId);
    }

    public List<ReceiveMessage> findOverdueOrder(List<Integer> stateList, String endGmtCreate) {
        if (CollectionUtils.isEmpty(stateList) || StringUtils.isEmpty(endGmtCreate)) {
            return Collections.emptyList();
        }
        return dbHelper.getAll(ReceiveMessage.class, "and gmt_create <= ? and handle_state=? ", endGmtCreate, stateList);
    }

}
